<style lang="scss" scoped="">
  .el-form .el-select {
    display: block;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  .view-list {
    > div {
      text-align: left;
      padding: 5px 0;
      display: flex;
      align-items: center;
      justify-content: space-between;
      &:hover {
        background: #f1f1f1;
      }
      &:first-child {
        font-weight: bold;
      }
      &:nth-child(2n) {
        background: #f7f7f7;
      }
      > div {
        width: 150px;
        &:first-child {
          width: 50px;
          padding-left: 10px;
        }
        &:last-child {
          width: 250px;
        }
      }
    }
  }
</style>
<template>
  <div>
    <h2 class="clearfix">{{currentForm.datasourceId ? '编辑' : '新增'}}数据源</h2>
    <el-form ref="dsForm" :model="currentForm" label-width="100px" :rules="rules"
             @submit.prevent="onSubmit('dsForm')" onsubmit="return false" v-show="step===1">
      <el-form-item label="标题" prop="name">
        <el-input type="text" v-model="currentForm.name" placeholder="请输入"></el-input>
      </el-form-item>

      <el-form-item label="类型" prop="type">
        <el-select v-model="currentForm.type" placeholder="请选择">
          <el-option value="database" label="数据库"></el-option>
          <el-option value="excel" label="excel"></el-option>
          <el-option value="csv" label="csv"></el-option>
        </el-select>
      </el-form-item>
      <template v-if="currentForm.type==='database'">
        <el-form-item label="数据库类型" prop="dbtype">
          <el-select v-model="currentForm.dbtype" placeholder="请选择" @change="dbTypeChange">
            <el-option v-for="item in dbTypeList" :value="item.type" :label="item.type" :key="item.type"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="地址" prop="url">
          <el-input type="text" v-model="currentForm.url" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="用户名" prop="userName">
          <el-input type="text" v-model="currentForm.userName" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="text" v-model="currentForm.password" placeholder="请输入"></el-input>
        </el-form-item>
      </template>
      <el-form-item label="文件编码" v-if="currentForm.type==='csv'" prop="encode">
        <el-input type="text" v-model="currentForm.encode" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item label="文件" v-if="currentForm.type==='excel'||currentForm.type==='csv'">
        <el-upload
          class="avatar-uploader"
          action="https://jsonplaceholder.typicode.com/posts/"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload">
          <i class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>

      <el-form-item label-width="100px">


        <template v-if="currentForm.type==='database'">
          <el-button type="primary" @click="testDb('dsForm')">测试</el-button>
          <el-button type="primary" @click="onSubmit('dsForm')" native-type="submit" v-if="isTest">下一步</el-button>
        </template>
        <template v-else="">
          <el-button type="primary" @click="onSubmit('dsForm')" native-type="submit">保存</el-button>
        </template>
        <el-button @click="doClose">取消</el-button>
      </el-form-item>
    </el-form>


    <div v-show="step==2">
      <div v-if="viewList.length>0" class="view-list">
        <div>
          <div>可见</div>
          <div>原名称</div>
          <div>
            显示名称
          </div>
        </div>
        <div v-for="view in viewList" @click="currentView=view">
          <el-switch v-model="view.checked" :active-value="1" :inactive-value="0" @change="changeViewCheck"></el-switch>
          <div>{{view.name}}</div>
          <div>
            <el-input type="text" v-model="view.title" placeholder="请输入" @change="changeView"></el-input>
          </div>
        </div>
      </div>
    </div>

  </div>
</template>

<script>
  import {database, http, datasource, dataset} from '@/resources';

  let defaultForm = {
    'datasourceId': '',
    'projectId': '',
    'name': '',
    'detail': '',
    'visiable': '1',
    'type': '',
    'dbtype': '',
    'driver': '',
    'url': '',
    'userName': '',
    'password': '',
    'encode': '',
    'fileId': ''
  };

  export default {
    name: 'editForm',
    mounted() {
      this.resetForm();
      this.getDbTypeList();
    },
    props: ['form'],
    data: function () {
      return {
        step: 1,
        imageUrl: '',
        currentForm: Object.assign({}, defaultForm),
        viewList: [],
        rules: {
          name: [
            {required: true, message: '标题', trigger: 'blur'}
          ],
          encode: [
            {required: true, message: '编码', trigger: 'blur'}
          ],
          url: [
            {required: true, message: '编码', trigger: 'blur'}
          ],
          dbtype: [
            {required: true, message: '编码', trigger: 'blur'}
          ],
          userName: [
            {required: true, message: '编码', trigger: 'blur'}
          ],
          password: [
            {required: true, message: '编码', trigger: 'blur'}
          ]
        },
        isTest: false,
        dbTypeList: [],
        currentView: {},
        isChange: false
      };
    },
    watch: {
      'form.datasourceId': function (s) {
        this.resetForm();
      }
    },
    methods: {
      resetForm() {
        this.currentForm = Object.assign({}, defaultForm, this.form);
        if (!this.currentForm.projectId) {
          this.currentForm.projectId = this.$route.params.projectId;
        }
        this.step = 1;
        this.viewList = [];
        this.isChange = false;
        this.$refs['dsForm'].resetFields();
      },
      changeDataSetList() {
        this.emitDataSoureInfo();
        http.get('/view', {params: {datasourceId: this.currentForm.datasourceId}}).then(res => {
          this.viewList = res.data.data;
          this.step = 2;
        });

      },
      onSubmit: function (formName) {
        let self = this;
        this.$refs[formName].validate((valid) => {
          if (!valid) {
            return false;
          }
          if (this.currentForm.datasourceId) {
            datasource.update(this.currentForm.datasourceId, this.currentForm).then(res => {
              this.changeDataSetList();
            });
          } else {
            datasource.save(this.currentForm).then(res => {
              this.currentForm.datasourceId = res.data.datasourceId;
              this.changeDataSetList();
            });
          }

        });
      },
      doClose: function () {

        this.$emit('close');
      },
      emitDataSoureInfo() {
        this.$emit('change', this.currentForm.datasourceId);
      },
      deleteItem: function () {

      },
      dbTypeChange(v) {
        for (let item of this.dbTypeList) {
          if (v === item.type) {
            this.currentForm.driver = item.driver;
            break;
          }
        }
      },
      testDb(formName) {
        this.$refs[formName].validate((valid) => {
          if (!valid || this.doing) {
            return false;
          }
          let dbTest = {
            'type': '',
            'dbtype': '',
            'driver': '',
            'url': '',
            'userName': '',
            'password': '',
            'encode': '',
            'fileId': ''
          };
          for (let i in dbTest) {
            dbTest[i] = this.currentForm[i];
          }

          http.post('/connect', dbTest).then(res => {
            if (res.data.code === 0) {
              this.$notify({
                message: '连接成功'
              });
              this.isTest = true;

            } else {
              this.$notify({
                message: res.data.msg
              });
            }

          });
        });
      },
      handleAvatarSuccess(res, file) {
        this.imageUrl = URL.createObjectURL(file.raw);
      },
      beforeAvatarUpload(file) {
        const isLt2M = file.size / 1024 / 1024 < 20;
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 20MB!');
        }
        return isLt2M;
      },
      getDbTypeList() {
        database.query().then(res => {
          this.dbTypeList = res.data.data;
        });
      },
      changeViewCheck(item) {
        if (!item && this.currentView.datasetId) {
          dataset.delete(this.currentView.datasetId);
        } else {
          dataset.save(Object.assign({}, this.currentView, {datasourceId: this.currentForm.datasourceId})).then(res => {
            this.currentView = Object.assign(this.currentView, {datasetId: res.data.datasetId});
          });
        }
        this.emitDataSoureInfo();
      },
      changeView(item) {
        if (this.currentView.datasetId) {
          dataset.update(this.currentView.datasetId, this.currentView);
          this.emitDataSoureInfo();
        }
      }

    }
  };
</script>
